package core

import (
	"github.com/garyburd/redigo/redis"
	"encoding/json"
	"fmt"
	"global/libs/structs"
)

const (
	DepthKey 			= "spider:%s:depths:%s"
)

func GetSpiderDepth(conn redis.Conn, exchangeName string, symbol string) (*structs.Depth, error) {
	var depth structs.Depth
	key := fmt.Sprintf(DepthKey, exchangeName, symbol)
	vals, err := redis.Bytes(conn.Do("HGET", key, "bids"))
	if err != nil {
		return nil, err
	}
	var bids [][]string
	err = json.Unmarshal(vals, &bids)
	if err != nil {
		return nil, err
	}

	depth.Bids = bids

	asksBytes, err := redis.Bytes(conn.Do("HGET", key, "asks"))
	if err != nil {
		return nil, err
	}
	var asks [][]string
	if err = json.Unmarshal(asksBytes, &asks); err != nil {
		return nil, err
	}
	depth.Asks = asks
	return &depth, nil
}

// 保存深度
func SaveDepth(conn redis.Conn, slug string, symbol structs.Symbol, depth structs.Depth) error {
	key := fmt.Sprintf(DepthKey, slug, symbol.From + "_" + symbol.To)
	bids, err := marshalDepth(depth.Bids)
	if err != nil {
		return err
	}

	asks, err := marshalDepth(depth.Asks)
	if err != nil {
		return err
	}

	conn.Send("MULTI")
	conn.Send("HSET", key, "bids", bids)
	conn.Send("HSET", key, "asks", asks)
	conn.Do("EXEC")
	return nil
}

// 对深度编码
func marshalDepth(data interface{}) (string, error) {
	dataBytes, err := json.Marshal(data)
	if err != nil {
		return "", err
	}
	return string(dataBytes), nil
}
